<!--
 * @Author: zk
 * @Date: 2021-01-19 14:03:40
 * @LastEditors: zk
 * @LastEditTime: 2021-01-20 14:55:17
 * @Description:
-->
<template>
  <departmentBase>
    <template v-slot:main-left>
      <SearchTrees
        :treeData="treeData"
        :lazy="lazy"
        :defaultProps="defaultProps"
        @getlazyLoad="lazyLoad"
        @deleteHandle="handleDelete"
        @handleNodeClickTree="handleNodeClickTree"
      />
    </template>
    <!-- 右侧部分 -->
    <template v-slot:search-info>
      <searchMain
        ref="searchMain"
        size="mini"
        :model="formData"
        :item-list="formItemList"
        :search-btn="searchBtn"
      />
    </template>
    <template v-slot:table-main>
      <div ref="depForm" class="depForm">
        <el-form
          ref="depRuleForm"
          :model="depForm"
          label-width="auto"
          class="demo-ruleForm"
          :rules="rules"
        >
          <div class="top">
            <el-form-item
              v-for="item in ItemList"
              :key="item.prop"
              :label="item.label"
              :prop="item.prop"
            >
              <el-input
                v-if="item.type === 'RegionCode'"
                v-model="depForm[item.prop]"
                :disabled="disabledRegionCode"
                :placeholder="item.placeholder"
              />
              <el-input
                v-if="item.type === 'Input'"
                v-model="depForm[item.prop]"
                :disabled="disabledItem"
                :placeholder="item.placeholder"
              />
              <el-select
                v-if="item.type === 'Select'"
                v-model="depForm[item.prop]"
                :style="{ width: '100%' }"
                :disabled="disabledItem"
                :placeholder="item.placeholder"
              >
                <el-option label="省" :value="1"></el-option>
                <el-option label="市" :value="2"></el-option>
                <el-option label="区" :value="3"></el-option>
                <el-option label="街道（镇）" :value="4"></el-option>
                <el-option label="社区（村）" :value="5"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="排序" v-show="codeShow">
              <el-input
                v-model="depForm.orderNum"
                :disabled="disabledItem"
              ></el-input>
            </el-form-item>
          </div>
          <div class="bottom">
            <el-form-item>
              <el-button
                :disabled="disabledItem"
                type="primary"
                @click="dialogStatus === 'create' ? createData() : updateData()"
                >确定</el-button
              >
              <el-button :disabled="disabledItem" @click="cancel"
                >取消</el-button
              >
            </el-form-item>
          </div>
        </el-form>
      </div>
    </template>
  </departmentBase>
</template>
<script>
import departmentBase from "@/components/Layout/departmentBase.vue"
import SearchTrees from "@/components/Trees/SearchTrees.vue"
import searchMain from "@/components/CommonForm/form-item/DepartmentForm.vue"
import { addressList, dataProps } from "@/simdata/healthData.js"
import success from "@/utils/operation-message.js"
import {
  addHisRegion,
  updateHisRegion,
  deleteRegion,
  getHisRegionMessage,
  initRegion,
  lazyRegion,
  lazyNodeRegion
} from "@/api/setup/region"
const defaultDic = {
  parentId: "1", // 上级父节点id
  orgId: "", // 机构id
  regionName: "", // 区划名称
  regionCode: "", // 区划编码
  regionLevel: "", // 区划级别
  orderNum: "" // 排序
}
export default {
  components: {
    departmentBase,
    SearchTrees,
    searchMain
  },
  data() {
    return {
      // 配置表单按钮
      searchBtn: [
        {
          label: "搜索",
          icon: "el-icon-search",
          type: "primary",
          disabled: false,
          handle: () => this.getAll()
        },
        {
          label: "新增",
          icon: "el-icon-circle-plus-outline",
          type: "primary",
          disabled: false,
          has: "region:add",
          handle: () => this.handleCreate()
        }
      ],
      formData: {
        regName: "" // 行政区划名称
      },
      formItemList: [
        {
          type: "Input",
          label: "",
          prop: "regName",
          span: 6,
          placeholder: "行政区划名称"
        }
      ],
      // 提交表单的字段
      depForm: Object.assign({}, defaultDic),
      // 验证字段
      rules: {
        regionCode: [{ required: true, message: "区划编码", trigger: "blur" }],
        regionName: [{ required: true, message: "区划名称", trigger: "blur" }],
        regionLevel: [{ required: true, message: "区划级别", trigger: "blur" }]
      },
      // 配置是否默认加载假数据
      lazy: true,
      treeData: [
        {
          children: [
            {
              children: [
                {
                  children: [
                    {
                      children: null,
                      hasChildrenId: null,
                      id: null,
                      isLeaf: true,
                      label: null,
                      orderNum: 0,
                      orgId: null,
                      parentId: "429037033000",
                      regionCode: "429037033005",
                      regionLevel: 5,
                      regionName: "五组"
                    }
                  ],
                  hasChildrenId: "429037033005",
                  id: null,
                  isLeaf: null,
                  label: null,
                  orderNum: 6,
                  orgId: null,
                  parentId: "429037000000",
                  regionCode: "429037033000",
                  regionLevel: 4,
                  regionName: "潜河村"
                }
              ],
              hasChildrenId: "429037053000",
              id: null,
              isLeaf: null,
              label: null,
              orderNum: 7,
              orgId: null,
              parentId: "429000000000",
              regionCode: "429037000000",
              regionLevel: 3,
              regionName: "竹根滩镇"
            }
          ],
          hasChildrenId: "429044000000",
          id: null,
          isLeaf: null,
          label: null,
          orderNum: 0,
          orgId: null,
          parentId: "1",
          regionCode: "429000000000",
          regionLevel: 2,
          regionName: "潜江市"
        }
      ],
      defaultProps: {
        label: "regionName",
        children: "children",
        isLeaf: "isLeaf"
      },
      code: "", // 编码验证
      disabledItem: true, // 控制input禁用
      disabledRegionCode: true, // 控制区划编码禁用
      codeShow: true, // 控制排序的显示隐藏
      dialogStatus: "", // 控制是新增还是修改
      // 配置显示的提交表单
      ItemList: [
        {
          type: "RegionCode",
          label: "区划编码",
          prop: "regionCode",
          disabled: true,
          placeholder: "请输入区划编码"
        },
        {
          type: "Input",
          label: "区划名称",
          prop: "regionName",
          disabled: true,
          placeholder: "请输入区划名称"
        },
        {
          type: "Select",
          label: "区划级别",
          prop: "regionLevel",
          options: [],
          disabled: true,
          placeholder: "请选择区划级别"
        }
        // {
        //   type: "Input",
        //   label: "排序",
        //   prop: "orderNum",
        //   disabled: true,
        //   placeholder: ""
        // }
      ],
      userInfo: JSON.parse(window.sessionStorage.getItem("userInfo"))
      // 默认加载数据
      // userInfo: {
      //   sysOrganizationId: "1001"
      // }
    }
  },
  methods: {
    //懒加载
    async lazyLoad(node, resolve) {
      console.log(node)
      this.depForm.regionName = this.formData.regName
      if (node.level === 0) {
        // if (this.depForm.regionName == "") {
        //   this.depForm.orgId = this.userInfo.sysOrganizationId
        // } else {
        //   this.depForm.parentId = ""
        // }
        const res = await lazyRegion(this.depForm)
        console.log(res)
        if (res.code === "1000") {
          this.treeData = res.data
          return resolve(this.treeData)
        }
      }
      if (node.level > 0) {
        const result = await lazyNodeRegion(node.data.regionCode)
        if (result.code === "1000") {
          return resolve(result.data)
        }
      }
    },
    // 点击树 回调
    handleNodeClickTree(data) {
      this.disabledItem = false
      this.disabledRegionCode = true
      this.codeShow = true
      this.depForm.regionName = data.regionName
      this.depForm.regionCode = data.regionCode
      this.depForm.regionLevel = data.regionLevel
      this.depForm.orderNum = data.orderNum
      this.depForm.parentId = data.parentId
      // 清除表单检验结果
      this.$nextTick(() => {
        this.$refs["depRuleForm"].clearValidate()
      })
    },
    // 取消按钮
    cancel() {
      this.resetForm()
      this.codeShow = true // 控制排序的显示
      this.disabledItem = true // 控制input禁用
      this.disabledRegionCode = true // 控制区划编码禁用
    },
    // 重置
    resetForm() {
      this.depForm = Object.assign({}, defaultDic)
    },
    // 添加
    handleCreate() {
      if (
        this.depForm.regionCode == "" ||
        this.depForm.regionCode == undefined
      ) {
        return this.$message.success("请先选择需要添加区划的上级区划!")
      }
      this.dialogStatus = "create"
      this.codeShow = false // 控制排序隐藏
      this.disabledItem = false // 控制input禁用
      this.disabledRegionCode = false
      this.code = this.depForm.regionCode
      console.log(this.depForm)
      this.resetTemp()
      this.$nextTick(() => {
        this.$refs["depRuleForm"].clearValidate()
      })
    },
    resetTemp() {
      this.depForm = {
        regionName: "",
        parentId: "",
        regionLevel: "",
        orderNum: ""
      }
    },
    // 点击确定提交
    createData() {
      this.$refs["depRuleForm"].validate(async valid => {
        if (valid) {
          this.depForm.parentId = this.code
          console.log(this.depForm)
          const res = await addHisRegion(this.depForm)
          if (res.code === "1000") {
            this.disabledItem = true // 控制input禁用
            this.disabledRegionCode = true
            success()
            this.resetTemp()
            this.getAll()
          }
        }
      })
    },
    // 修改提交
    async updateData() {
      this.$nextTick(() => {
        this.$refs["depRuleForm"].clearValidate()
      })
      const res = await updateHisRegion(this.depForm)
      console.log(res)
      if (res.code === "1000") {
        this.resetTemp()
        this.getAll()
      }
    },
    //删除
    handleDelete(node, data) {
      // if (node.data.isLeaf != true) {
      //   this.$message({
      //     message: "请先删除下级区划!",
      //     type: "error",
      //     duration: 2000
      //   })
      //   return
      // }
      console.log(node.data.isLeaf)
      if (node.data.isLeaf != true) {
        this.$confirm("此操作将删除子级所有数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            deleteRegion(this.depForm.regionCode).then(response => {
              console.log(response)
              this.$message({
                type: "success",
                message: response.msg
              })
              this.resetTemp()
              this.getAll()
            })
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            })
          })
      } else {
        this.$confirm("此操作将删除该记录, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            deleteRegion(this.depForm.regionCode).then(response => {
              console.log(response)

              this.$message({
                type: "success",
                message: response.msg
              })
              this.resetTemp()
              this.getAll()
            })
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            })
          })
      }
    },
    async getAll() {
      this.depForm.regionName = this.formData.regName
      // 获取所有行政区域区划信息
      // this.dialogFormVisiblePower = true;
      if (this.depForm.regionName == "") {
        this.depForm.orgId = this.userInfo.sysOrganizationId
        this.depForm.parentId = "1"
      } else {
        this.depForm.parentId = ""
      }
      console.log(this.depForm)
      const res = await lazyRegion(this.depForm)
      console.log(res)
      if (res.code === "1000") {
        this.treeData = res.data
        this.dialogStatus = ""
        this.cancel()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ .table-item {
  height: 100%;
  margin-right: 0 !important;
}
.depForm {
  height: 100%;
  .el-form {
    width: 80%;
    height: 100%;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    .top {
      flex: 1;
      padding: 20px 0;
      overflow: hidden;
      overflow-y: auto;
      padding-right: 30px;
    }
    .bottom {
      .el-form-item {
        height: 80px;
        /deep/ .el-form-item__content {
          padding-top: 30px;
        }
      }
    }
  }
}
</style>
